package com.example.beikeyigou.pay;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.beikeyigou.R;
import com.example.beikeyigou.dialog.PromptDialog;
import com.example.beikeyigou.login_reg.UserBean;
import com.example.beikeyigou.trolley.TrolleyBean;
import com.example.beikeyigou.utils.SaveUserUtils;
import com.example.beikeyigou.utils.URLUtils;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class PayActivity extends AppCompatActivity {
    private TextView nameTv, phoneTv, addressTv, numTv, priceTv;
    private ListView goodsLv;
    private ImageView backImg;
    private Button buyBtn;

    UserBean.DataBean userData;
    List<TrolleyBean.DataBean> TrolleyData;
    Map<String, String> goodMap;
    PayAdapter adapter;
    BigDecimal allPrice;
    int flag;               // 标志位：1.从商品详情页直接购买；2.从购物车购买

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);

        Intent intent = getIntent();
        flag = intent.getIntExtra("flag", 0);
        Bundle bundle = intent.getExtras();
        if (flag == 1) {
            goodMap = (Map<String, String>) bundle.getSerializable("mapData");
        } else if (flag == 2) {
            TrolleyData = (List<TrolleyBean.DataBean>) bundle.getSerializable("trolleyData");
        }
        
        findView();
        initData();
        setListener();
        changeStatusBarTextImgColor(true);
    }

    public void changeStatusBarTextImgColor(boolean color) {
        if (color) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//实现状态栏图标和文字颜色为暗色
        } else {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);//恢复状态栏白色字体
        }
    }

    private void setListener() {
        backImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        buyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag == 1) {
                    Map<String, String> map = new HashMap<>();
                    map.put("count", goodMap.get("count"));
                    map.put("userId", String.valueOf(userData.getId()));
                    map.put("commodityId", goodMap.get("commodityId"));
                    RequestParams params = new RequestParams(URLUtils.insertBought_url);
                    // 将提交的键值对放到请求参数中
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        params.addParameter(key, map.get(key));
                    }
                    params.setAsJsonContent(true);
                    params.setBodyContentType("application/json;charset=utf-8");

                    x.http().post(params, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String result) {
                            PromptDialog dialog = new PromptDialog(PayActivity.this);
                            dialog.show();
                            dialog.setPromptTv("购买成功！")
                                    .setOnClickBottomListener(new PromptDialog.OnClickBottomListener() {
                                        @Override
                                        public void onPositiveClick() {
                                            finish();
                                        }

                                        @Override
                                        public void onNegtiveClick() {
                                            finish();
                                        }
                                    });
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {

                        }

                        @Override
                        public void onCancelled(CancelledException cex) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });
                } else if (flag == 2) {
                    List<SelectGood> goodsPay = new ArrayList<>();
                    for (int i = 0; i < TrolleyData.size(); ++i) {
                        goodsPay.add(new SelectGood(TrolleyData.get(i).getId(), userData.getId()
                                , TrolleyData.get(i).getCommodityId(), TrolleyData.get(i).getCount()));
                    }
                    String string = (new Gson()).toJson(goodsPay);
                    // 网络请求
                    RequestParams params = new RequestParams(URLUtils.orderShopping_url);
                    // 将提交的键值对放到请求参数中
                    params.setBodyContent(string);
                    params.setAsJsonContent(true);
                    params.setBodyContentType("application/json;charset=utf-8");

                    x.http().post(params, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String result) {
                            PromptDialog dialog = new PromptDialog(PayActivity.this);
                            dialog.show();
                            dialog.setPromptTv("购买成功！")
                                    .setOnClickBottomListener(new PromptDialog.OnClickBottomListener() {
                                        @Override
                                        public void onPositiveClick() {
                                            finish();
                                        }

                                        @Override
                                        public void onNegtiveClick() {
                                            finish();
                                        }
                                    });
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            Toast.makeText(PayActivity.this, "error", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onCancelled(CancelledException cex) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });
                }
            }
        });
    }

    private void initData() {
        allPrice = new BigDecimal("0");
        userData = SaveUserUtils.getUserData(this);
        if (flag == 1) {
            List<TrolleyBean.DataBean> tempData = new ArrayList<>();
            tempData.add(new TrolleyBean.DataBean(Integer.parseInt(goodMap.get("count")), goodMap.get("commodityName")
                    , goodMap.get("photo"), Double.parseDouble(goodMap.get("totalPrice"))));
            adapter = new PayAdapter(this, tempData);
            allPrice = new BigDecimal(goodMap.get("totalPrice"));
            numTv.setText("已选1件，");
        } else if (flag == 2) {
            adapter = new PayAdapter(this, TrolleyData);
            for (int i = 0; i < TrolleyData.size(); ++i) {
                allPrice = allPrice.add(new BigDecimal(String.valueOf(TrolleyData.get(i).getTotalprices())));
            }
            numTv.setText("已选" + String.valueOf(TrolleyData.size()) + "件，");
        }
        priceTv.setText("￥" + allPrice.toString());
        goodsLv.setAdapter(adapter);
        // ListView嵌套在ScrollView中只显示一个item，因此需要手动设置ListView的高度
        int totalHeight = 0;
        for (int i = 0, len = adapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = adapter.getView(i, null, goodsLv);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = goodsLv.getLayoutParams();
        params.height = totalHeight + (goodsLv.getDividerHeight() * (goodsLv.getCount() - 1)) + 30;
        goodsLv.setLayoutParams(params);

        nameTv.setText(userData.getName());
        phoneTv.setText(userData.getPhone());
        addressTv.setText(userData.getAddress());
    }

    private void findView() {
        backImg = findViewById(R.id.pay_iv_back);
        nameTv = findViewById(R.id.pay_name_tv);
        phoneTv = findViewById(R.id.pay_phone_tv);
        addressTv = findViewById(R.id.pay_address_tv);
        numTv = findViewById(R.id.pay_num);
        priceTv = findViewById(R.id.pay_all_price);
        goodsLv = findViewById(R.id.pay_lv);
        buyBtn = findViewById(R.id.pay_btn);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
}